package category

import (
	"context"
	"github.com/pkg/errors"
	"github.com/xinliangnote/go-gin-api/configs"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
)

func NewModel() *Category {
	return new(Category)
}

func (p *Category) Create(db *mongo.Client) (id string, err error) {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("category")
	p.IsDel = 0
	one, err := client.InsertOne(context.TODO(), p)
	if err != nil {
		return "", err
	}
	return one.InsertedID.(primitive.ObjectID).String(), nil
}

func (p *Category) List(db *mongo.Client, pageIndex uint, pageSize uint) (list []Category, err error) {
	var productList []Category

	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("category")
	//skip := int64((pageIndex - 1) * pageSize)
	//findOptions := options.Find()
	//findOptions.SetSort(bson.D{{"_id", -1}})
	//findOptions.SetSkip(skip)
	//findOptions.SetLimit(int64(pageSize))

	find, err := client.Find(context.TODO(), bson.D{})
	if err != nil && !errors.Is(err, mongo.ErrNoDocuments) {
		return nil, err
	}

	err = find.All(context.TODO(), &productList)
	if err != nil {
		return nil, err
	}

	return productList, nil
}

func (p *Category) Update(db *mongo.Client) error {
	cfg := configs.Get().Mongodb
	client := db.Database(cfg.Config.Name).Collection("category")
	objId, _ := primitive.ObjectIDFromHex(p.Id)
	filter := bson.D{{"_id", objId}}

	params := bson.M{}

	if p.Name != "" {
		params["name"] = p.Name
	}

	if p.Desc != "" {
		params["desc"] = p.Desc
	}

	if p.IsDel != 0 {
		params["isDel"] = 1
	}
	update := bson.M{"$set": params}

	product := new(Category)
	_ = client.FindOne(context.TODO(), filter).Decode(&product)

	_, err := client.UpdateOne(context.TODO(), filter, update)
	return err
}
